﻿using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;

namespace FileMatcher
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            Title = Strings.AppName + " (Version " + Assembly.GetExecutingAssembly().GetName().Version + ")";
        }

        void AddFolder(string folder)
        {
            if (!lstFolders.Items.Contains(folder))
            {
                lstFolders.Items.Add(folder);
            }
        }

        private void BtnRemoveFolderClick(object sender, RoutedEventArgs e)
        {
            if (lstFolders.SelectedIndex < 0)
            {
                return;
            }
            lstFolders.Items.RemoveAt(lstFolders.SelectedIndex);
        }

        private void BtnAddFolderClick(object sender, RoutedEventArgs e)
        {
            var folder = txtFileToAdd.Text;
            if (!Directory.Exists(folder))
            {
                MessageBox.Show("Please input a valid folder path", Strings.AppName);
                return;
            }
            AddFolder(folder);
        }

        private void TxtFileToAdd_OnPreviewDrop(object sender, DragEventArgs e)
        {
        }

        private void LstFolders_OnPreviewDrop(object sender, DragEventArgs e)
        {
            var added = false;
            foreach (var ss in e.Data.GetFormats().Select(f => e.Data.GetData(f)).OfType<string[]>())
            {
                foreach (var s in ss.Where(Directory.Exists))
                {
                    AddFolder(s);
                    added = true;
                }
                if (added)
                {
                    break;
                }
            }

            e.Handled = true;
        }

        private void MainWindow_OnPreviewDrop(object sender, DragEventArgs e)
        {

        }

        private void BtnRedundantClick(object sender, RoutedEventArgs e)
        {
            var folders = lstFolders.Items.Cast<string>().ToList();
            var fm = new FileMatcherLib.FileMatcher(folders);

            var rs = new RedunduncySummary(fm)
                {
                    Owner = this,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner
                };
            rs.ShowDialog();
        }

        private void LstFolders_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            btnRemoveFolder.IsEnabled = lstFolders.SelectedItems.Count > 0;
        }

        private void TxtFileToAdd_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            btnAddFolder.IsEnabled = txtFileToAdd.Text.Trim() != "";
        }
    }
}
